#include ".\groupconfigview.h"
#include <QVBoxLayout>
#include <QScrollArea>
#include <QGroupBox>
#include <QGridLayout>
#include <QLabel>
#include <QPushButton>
#include <QButtonGroup>
#include <QRadioButton>
#include <QSpinBox>
#include <QDoubleSpinBox>
#include <QComboBox>
#include <QCheckBox>
#include <QLineEdit>
#include <QSpacerItem>
#include <QJsonObject>
#include <QJsonArray>
#include <QDebug>
#include <QMessageBox>


GroupConfigView::GroupConfigView(QObject *parent)
    : ConfigView(parent)
{
    m_view = new QWidget();
    QVBoxLayout *mainLayout = new QVBoxLayout(m_view);
    mainLayout->setContentsMargins(0, 0, 0, 0);

    // 创建滚动区域
    m_scrollArea = new QScrollArea();
    m_scrollArea->setWidgetResizable(true);
    m_scrollArea->setFrameShape(QFrame::NoFrame);

    m_scrollContent = new QWidget();
    QVBoxLayout *contentLayout = new QVBoxLayout(m_scrollContent);
    contentLayout->setAlignment(Qt::AlignTop);

    m_scrollArea->setWidget(m_scrollContent);
    mainLayout->addWidget(m_scrollArea);
}

GroupConfigView::~GroupConfigView()
{
    if (m_view) {
        delete m_view;
    }
}

QWidget* GroupConfigView::viewWidget()
{
    return m_view;
}

void GroupConfigView::updateConfig(const QJsonArray &config)
{
    m_originalConfig = config;
    m_currentConfig = config;
    clearView();

    QVBoxLayout *contentLayout = qobject_cast<QVBoxLayout*>(m_scrollContent->layout());
    if (!contentLayout) {
        contentLayout = new QVBoxLayout(m_scrollContent);
        contentLayout->setAlignment(Qt::AlignTop);
    }

    // 检查下载模式配置
    int sop2Index = -1;
    int bootIndex = -1;
    bool hasSOP2 = false;
    bool hasBOOT = false;

    for (int i = 0; i < m_currentConfig.size(); i++) {
        QJsonObject obj = m_currentConfig[i].toObject();
        if (obj["type"].toString() == "down_sop2") {
            sop2Index = i;
            hasSOP2 = true;
        } else if (obj["type"].toString() == "down_boot") {
            bootIndex = i;
            hasBOOT = true;
        }
    }

    // 创建下载模式选择器
    if (hasSOP2 || hasBOOT) {
        QGroupBox *modeGroup = new QGroupBox("下载模式配置");
        modeGroup->setStyleSheet(
            "QGroupBox {"
            "   border: 1px solid #aaa;"
            "   border-radius: 5px;"
            "   margin-top: 10px;"
            "   font-weight: bold;"
            "}"
            "QGroupBox::title {"
            "   subcontrol-origin: margin;"
            "   padding: 0 5px;"
            "   background-color: #e9e9e9;"
            "}"
        );

        QHBoxLayout *modeLayout = new QHBoxLayout(modeGroup);

        QButtonGroup *buttonGroup = new QButtonGroup(this);
        QRadioButton *sop2Radio = new QRadioButton("SOP2模式");
        QRadioButton *bootRadio = new QRadioButton("BOOT模式");

        buttonGroup->addButton(sop2Radio);
        buttonGroup->addButton(bootRadio);
        modeLayout->addWidget(sop2Radio);
        modeLayout->addWidget(bootRadio);

        if (hasSOP2) sop2Radio->setChecked(true);
        if (hasBOOT) bootRadio->setChecked(true);

        // 处理模式切换
        connect(buttonGroup, QOverload<QAbstractButton*>::of(&QButtonGroup::buttonClicked),
                this, &GroupConfigView::handleModeButtonClicked);

        contentLayout->addWidget(modeGroup);
    }

    // 动态构建分组视图
    for (int configIndex = 0; configIndex < m_currentConfig.size(); configIndex++) {
        QJsonValue configVal = m_currentConfig[configIndex];
        QJsonObject configObj = configVal.toObject();
        QString type = configObj["type"].toString();

        // 跳过下载模式配置（已在上面处理）
        if (type == "down_sop2" || type == "down_boot") continue;

        // 创建分组框
        QGroupBox *groupBox = new QGroupBox(type.toUpper() + " 配置");
        groupBox->setStyleSheet(
            "QGroupBox {"
            "   border: 1px solid #aaa;"
            "   border-radius: 5px;"
            "   margin-top: 10px;"
            "   font-weight: bold;"
            "}"
            "QGroupBox::title {"
            "   subcontrol-origin: margin;"
            "   padding: 0 5px;"
            "   background-color: #e9e9e9;"
            "}"
        );

        QGridLayout *gridLayout = new QGridLayout(groupBox);
        gridLayout->setColumnStretch(1, 1); // 第二列拉伸

        int row = 0;

        // 处理不同类型的配置
        if (configObj.contains("config")) {
            QJsonValue configValue = configObj["config"];

            if (type == "io") {
                QJsonArray ioArray = configValue.toArray();
                for (int itemIndex = 0; itemIndex < ioArray.size(); itemIndex++) {
                    QJsonValue ioVal = ioArray[itemIndex];
                    QJsonObject ioObj = ioVal.toObject();

                    gridLayout->addWidget(new QLabel("引脚:"), row, 0);
                    // 引脚号可编辑
                    QWidget *pinWidget = createEditableWidget("io_pin", ioObj["io_pin"], configIndex, itemIndex);
                    gridLayout->addWidget(pinWidget, row, 1);

                    gridLayout->addWidget(new QLabel("模式:"), row, 2);
                    QWidget *modeWidget = createEditableWidget("mode", ioObj["mode"], configIndex, itemIndex);
                    gridLayout->addWidget(modeWidget, row, 3);

                    // 当模式为输出、输入或PWM时显示激活状态
                    QString mode = ioObj["mode"].toString();
                    if (mode == "output" || mode == "input" || mode == "pwm") {
                        gridLayout->addWidget(new QLabel("激活状态:"), row, 4);
                        QWidget *stateWidget = createEditableWidget("active_state", ioObj["active_state"], configIndex, itemIndex);
                        gridLayout->addWidget(stateWidget, row, 5);
                    }

                    // 删除按钮
                    QPushButton *deleteButton = new QPushButton("删除");
                    deleteButton->setStyleSheet(
                        "QPushButton {"
                        "   background-color: #e74c3c;"
                        "   color: white;"
                        "   padding: 4px 8px;"
                        "   border-radius: 4px;"
                        "}"
                        "QPushButton:hover { background-color: #c0392b; }"
                    );
                    connect(deleteButton, &QPushButton::clicked, this, [this, configIndex, itemIndex]() {
                        if (configIndex < 0 || configIndex >= m_currentConfig.size()) return;

                        QJsonObject configObj = m_currentConfig[configIndex].toObject();
                        if (!configObj.contains("config")) return;

                        QJsonValue configValue = configObj["config"];
                        if (!configValue.isArray()) return;

                        QJsonArray ioArray = configValue.toArray();
                        if (itemIndex < 0 || itemIndex >= ioArray.size()) return;

                        ioArray.removeAt(itemIndex);

                        configObj["config"] = ioArray;
                        m_currentConfig[configIndex] = configObj;

                        updateConfig(m_currentConfig);
                    });
                    gridLayout->addWidget(deleteButton, row, 6);

                    row++;
                }

                // 添加引脚按钮
                QPushButton *addPinButton = new QPushButton("添加引脚");
                addPinButton->setStyleSheet(
                    "QPushButton {"
                    "   background-color: #3498db;"
                    "   color: white;"
                    "   padding: 6px 12px;"
                    "   border-radius: 4px;"
                    "}"
                    "QPushButton:hover { background-color: #2980b9; }"
                );
                connect(addPinButton, &QPushButton::clicked, this, [this, configIndex]() {
                    if (configIndex < 0 || configIndex >= m_currentConfig.size()) return;

                    QJsonObject configObj = m_currentConfig[configIndex].toObject();
                    if (!configObj.contains("config")) return;

                    QJsonValue configValue = configObj["config"];
                    if (!configValue.isArray()) return;

                    QJsonArray ioArray = configValue.toArray();

                    QJsonObject newPin;
                    newPin["io_pin"] = 0;
                    newPin["mode"] = "input";
                    newPin["active_state"] = false;

                    ioArray.append(newPin);

                    configObj["config"] = ioArray;
                    m_currentConfig[configIndex] = configObj;

                    updateConfig(m_currentConfig);
                });
                gridLayout->addWidget(addPinButton, row, 0, 1, 7);
                row++;
            }
            else if (type == "adc") {
                QJsonObject adcObj = configValue.toObject();
                QJsonArray channels = adcObj["channels"].toArray();

                gridLayout->addWidget(new QLabel("通道数量:"), row, 0);
                gridLayout->addWidget(new QLabel(QString::number(channels.size())), row, 1);
                row++;

                gridLayout->addWidget(new QLabel("通道列表:"), row, 0);

                // 通道顺序编辑
                for (int i = 0; i < channels.size(); i++) {
                    QHBoxLayout *channelLayout = new QHBoxLayout();

                    // 通道显示
                    QLineEdit *channelEdit = new QLineEdit(channels[i].toString());
                    channelLayout->addWidget(channelEdit);

                    // 上移按钮
                    if (i > 0) {
                        QPushButton *upButton = new QPushButton("↑");
                        upButton->setFixedWidth(30);
                        connect(upButton, &QPushButton::clicked, this, [this, configIndex, i]() {
                            handleAdcChannelMove(true, configIndex, i);
                        });
                        channelLayout->addWidget(upButton);
                    }

                    // 下移按钮
                    if (i < channels.size()-1) {
                        QPushButton *downButton = new QPushButton("↓");
                        downButton->setFixedWidth(30);
                        connect(downButton, &QPushButton::clicked, this, [this, configIndex, i]() {
                            handleAdcChannelMove(false, configIndex, i);
                        });
                        channelLayout->addWidget(downButton);
                    }

                    // 连接通道名称编辑的信号
                    connect(channelEdit, &QLineEdit::textChanged, this, [this, configIndex, i, channelEdit]() {
                        handleAdcChannelEdit(channelEdit->text(), configIndex, i);
                    });

                    gridLayout->addLayout(channelLayout, row, 1, 1, 6);
                    row++;
                }

                // 添加通道按钮
                QPushButton *addChannelButton = new QPushButton("添加通道");
                addChannelButton->setStyleSheet(
                    "QPushButton {"
                    "   background-color: #3498db;"
                    "   color: white;"
                    "   padding: 6px 12px;"
                    "   border-radius: 4px;"
                    "}"
                    "QPushButton:hover { background-color: #2980b9; }"
                );
                connect(addChannelButton, &QPushButton::clicked, this, [this, configIndex]() {
                    if (configIndex < 0 || configIndex >= m_currentConfig.size()) return;

                    QJsonObject configObj = m_currentConfig[configIndex].toObject();
                    if (!configObj.contains("config")) return;

                    QJsonValue configValue = configObj["config"];
                    if (!configValue.isObject()) return;

                    QJsonObject adcObj = configValue.toObject();
                    QJsonArray channels = adcObj["channels"].toArray();

                    channels.append("新通道");

                    adcObj["channels"] = channels;
                    configObj["config"] = adcObj;
                    m_currentConfig[configIndex] = configObj;

                    updateConfig(m_currentConfig);
                });
                gridLayout->addWidget(addChannelButton, row, 0, 1, 7);
                row++;
            }
        }

        contentLayout->addWidget(groupBox);
    }

    // 添加操作按钮
    QWidget *buttonContainer = new QWidget();
    QHBoxLayout *buttonLayout = new QHBoxLayout(buttonContainer);
    buttonLayout->setContentsMargins(10, 10, 10, 10);

    QPushButton *applyButton = new QPushButton("应用修改");
    applyButton->setStyleSheet(
        "QPushButton {"
        "   background-color: #4CAF50;"
        "   color: white;"
        "   padding: 8px 16px;"
        "   border-radius: 4px;"
        "}"
        "QPushButton:hover { background-color: #45a049; }"
    );
    connect(applyButton, &QPushButton::clicked, this, &GroupConfigView::applyEdits);

    QPushButton *resetButton = new QPushButton("重置修改");
    resetButton->setStyleSheet(
        "QPushButton {"
        "   background-color: #f0ad4e;"
        "   color: white;"
        "   padding: 8px 16px;"
        "   border-radius: 4px;"
        "}"
        "QPushButton:hover { background-color: #ec971f; }"
    );
    connect(resetButton, &QPushButton::clicked, this, &GroupConfigView::resetToOriginal);

    QPushButton *sendDataButton = new QPushButton("配置参数");
    sendDataButton->setStyleSheet(
        "QPushButton {"
        "   background-color: #4CAF50;"
        "   color: white;"
        "   padding: 8px 16px;"
        "   border-radius: 4px;"
        "}"
        "QPushButton:hover { background-color: #45a049; }"
    );
    emit sig_sendConfigData(getModifiedConfig());

    buttonLayout->addStretch();
    buttonLayout->addWidget(applyButton);
    buttonLayout->addWidget(resetButton);
    buttonLayout->addWidget(sendDataButton);

    contentLayout->addWidget(buttonContainer);
    contentLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::Expanding));
}

QJsonArray GroupConfigView::getModifiedConfig() const
{
    return m_currentConfig;
}

void GroupConfigView::applyEdits()
{
    // 遍历所有编辑控件，更新配置
    for (auto it = m_editWidgets.begin(); it != m_editWidgets.end(); ++it) {
        QWidget *widget = it.key();
        int configIndex = it.value().first;
        int itemIndex = it.value().second.first;
        QString key = it.value().second.second;

        if (configIndex < 0 || configIndex >= m_currentConfig.size()) continue;

        QJsonObject configObj = m_currentConfig[configIndex].toObject();
        if (configObj.contains("config")) {
            QJsonValue configValue = configObj["config"];

            if (itemIndex >= 0) {
                // 数组项中的值
                if (configValue.isArray()) {
                    QJsonArray configArray = configValue.toArray();
                    if (itemIndex < configArray.size()) {
                        QJsonObject itemObj = configArray[itemIndex].toObject();
                        itemObj[key] = getValueFromWidget(widget);
                        configArray[itemIndex] = itemObj;
                        configObj["config"] = configArray;
                    }
                }
            } else {
                // 直接配置值
                if (configValue.isObject()) {
                    QJsonObject configObjValue = configValue.toObject();
                    configObjValue[key] = getValueFromWidget(widget);
                    configObj["config"] = configObjValue;
                }
            }

            m_currentConfig[configIndex] = configObj;
        }
    }

    emit configModified();
}

void GroupConfigView::resetToOriginal()
{
    m_currentConfig = m_originalConfig;
    updateConfig(m_currentConfig);
}

void GroupConfigView::clearView()
{
    if (!m_scrollContent) return;

    QLayout *contentLayout = m_scrollContent->layout();
    if (contentLayout) {
        QLayoutItem *child;
        while ((child = contentLayout->takeAt(0)) != nullptr) {
            delete child->widget();
            delete child;
        }
    }

    m_editWidgets.clear();
}

QWidget* GroupConfigView::createEditableWidget(const QString &key, const QJsonValue &value,
                                             int configIndex, int itemIndex)
{
    QWidget *container = new QWidget();
    QHBoxLayout *layout = new QHBoxLayout(container);
    layout->setContentsMargins(0, 0, 0, 0);

    if (value.isBool()) {
        QCheckBox *checkBox = new QCheckBox();
        checkBox->setChecked(value.toBool());
        layout->addWidget(checkBox);
        m_editWidgets[checkBox] = qMakePair(configIndex, qMakePair(itemIndex, key));
    }
    else if (value.isDouble()) {
        double num = value.toDouble();
        if (qFloor(num) == num) { // 整数
            QSpinBox *spinBox = new QSpinBox();
            spinBox->setValue(static_cast<int>(num));
            spinBox->setRange(0, 100);
            spinBox->setSingleStep(1);
            layout->addWidget(spinBox);
            m_editWidgets[spinBox] = qMakePair(configIndex, qMakePair(itemIndex, key));
        } else { // 浮点数
            QDoubleSpinBox *spinBox = new QDoubleSpinBox();
            spinBox->setValue(num);
            spinBox->setRange(0, 100);
            spinBox->setSingleStep(0.1);
            layout->addWidget(spinBox);
            m_editWidgets[spinBox] = qMakePair(configIndex, qMakePair(itemIndex, key));
        }
    }
    else if (value.isString()) {
        // 引脚号使用QSpinBox
        if (key == "io_pin" || key == "output_pin") {
            QSpinBox *spinBox = new QSpinBox();
            spinBox->setValue(value.toInt());
            spinBox->setRange(0, 100);
            spinBox->setSingleStep(1);
            layout->addWidget(spinBox);
            m_editWidgets[spinBox] = qMakePair(configIndex, qMakePair(itemIndex, key));
        }
        // 模式选择使用QComboBox
        else if (key == "mode") {
            QComboBox *comboBox = new QComboBox();
            comboBox->addItems({"input", "output", "analog", "pwm"});
            comboBox->setCurrentText(value.toString());
            layout->addWidget(comboBox);
            m_editWidgets[comboBox] = qMakePair(configIndex, qMakePair(itemIndex, key));
        }
        // 其他字符串使用QLineEdit
        else {
            QLineEdit *lineEdit = new QLineEdit(value.toString());
            layout->addWidget(lineEdit);
            m_editWidgets[lineEdit] = qMakePair(configIndex, qMakePair(itemIndex, key));
        }
    }
    else {
        QLabel *label = new QLabel(value.toVariant().toString());
        layout->addWidget(label);
    }

    return container;
}

QJsonValue GroupConfigView::getValueFromWidget(QWidget *widget) const
{
    if (QCheckBox *checkBox = qobject_cast<QCheckBox*>(widget)) {
        return checkBox->isChecked();
    }
    else if (QComboBox *comboBox = qobject_cast<QComboBox*>(widget)) {
        return comboBox->currentText();
    }
    else if (QLineEdit *lineEdit = qobject_cast<QLineEdit*>(widget)) {
        return lineEdit->text();
    }
    else if (QDoubleSpinBox *spinBox = qobject_cast<QDoubleSpinBox*>(widget)) {
        return spinBox->value();
    }
    else if (QSpinBox *spinBox = qobject_cast<QSpinBox*>(widget)) {
        return spinBox->value();
    }

    return QJsonValue();
}

void GroupConfigView::handleModeButtonClicked(QAbstractButton *button)
{
    qDebug() << "handleModeButtonClicked: " << button->text();
    // 删除所有下载模式配置
    for (int i = m_currentConfig.size()-1; i >=0; i--) {
        QString type = m_currentConfig[i].toObject()["type"].toString();
        if (type == "down_sop2" || type == "down_boot") {
            m_currentConfig.removeAt(i);
        }
    }

    if (button->text() == "SOP2模式") {
        // 添加SOP2配置
        QJsonObject sop2Config;
        sop2Config["type"] = "down_sop2";
        QJsonObject config;
        config["device"] = "default";
        config["output_pin"] = 0;
        sop2Config["config"] = config;
        m_currentConfig.append(sop2Config);
    }
    else if (button->text() == "BOOT模式") {
        // 添加BOOT配置
        QJsonObject bootConfig;
        bootConfig["type"] = "down_boot";
        QJsonObject config;
        config["device"] = "default";
        config["output_pin"] = 0;
        config["control"] = QJsonArray();
        bootConfig["config"] = config;
        m_currentConfig.append(bootConfig);
    }

    updateConfig(m_currentConfig);
}

void GroupConfigView::handleAdcChannelMove(bool up, int configIndex, int channelIndex)
{
    if (configIndex < 0 || configIndex >= m_currentConfig.size()) return;

    QJsonObject configObj = m_currentConfig[configIndex].toObject();
    if (!configObj.contains("config")) return;

    QJsonValue configValue = configObj["config"];
    if (!configValue.isObject()) return;

    QJsonObject adcObj = configValue.toObject();
    QJsonArray channels = adcObj["channels"].toArray();
    if (channelIndex >= channels.size()) return;

    int newIndex = up ? channelIndex - 1 : channelIndex + 1;
    if (newIndex < 0 || newIndex >= channels.size()) return;

    // 交换位置
    QJsonValue temp = channels[channelIndex];
    channels[channelIndex] = channels[newIndex];
    channels[newIndex] = temp;

    // 更新配置
    adcObj["channels"] = channels;
    configObj["config"] = adcObj;
    m_currentConfig[configIndex] = configObj;

    // 刷新视图
    updateConfig(m_currentConfig);
}

void GroupConfigView::handleAdcChannelEdit(const QString &text, int configIndex, int channelIndex)
{
    if (configIndex < 0 || configIndex >= m_currentConfig.size()) return;

    QJsonObject configObj = m_currentConfig[configIndex].toObject();
    if (!configObj.contains("config")) return;

    QJsonValue configValue = configObj["config"];
    if (!configValue.isObject()) return;

    QJsonObject adcObj = configValue.toObject();
    QJsonArray channels = adcObj["channels"].toArray();
    if (channelIndex >= channels.size()) return;

    // 更新通道名称
    channels[channelIndex] = text;

    // 更新配置
    adcObj["channels"] = channels;
    configObj["config"] = adcObj;
    m_currentConfig[configIndex] = configObj;
}
